import { reqGetUserInfo, login, reqGetUserDetailById } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router' // 重置路由

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {},
  }
}

const state = getDefaultState()

// 一、user的mutations方法
const mutations = {
  // 1.1 设置token
  setToken(state, token) {
    state.token = token
    // 保存到本地
    setToken(token)
  },
  // 1.2 设置用户信息
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 1.3 移除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  },
  // 1.4 移除token
  removeToken(state) {
    state.token = null
    // 移除本地token
    removeToken()
  },
}

// 二、user的actions
const actions = {
  // 2.1 登录
  async login({ commit }, data) {
    try {
      const res = await login(data)
      commit('setToken', res)
      return res
    } catch (error) {
      return new Promise(error)
    }
  },

  // 2.2 获取用户信息
  async getUserInfoAsync({ commit }) {
    const res1 = await reqGetUserInfo()
    const res2 = await reqGetUserDetailById(res1.userId)
    // console.log(res1)
    // console.log(res2)
    const baseResult = { ...res1, ...res2 }
    // console.log(baseResult)
    commit('setUserInfo', baseResult)
    return baseResult
  },

  // 2.3 退出登录
  logout({ commit }) {
    commit('removeToken') // 删除token
    commit('removeUserInfo') // 删除用户信息
    resetRouter() // 重置路由
    commit('permission/setRoutes', [], { root: true }) // 重置 vuex 中的路由信息
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
